﻿
namespace zijian666.Data;

internal class DynamicRecord(Dictionary<string, int> indexer, object?[] record)
    : DynamicDictionary(record)
{
    private readonly Dictionary<string, int> _indexer = indexer ?? throw new ArgumentNullException(nameof(indexer));
    private readonly object?[] _record = record ?? throw new ArgumentNullException(nameof(record));

    protected override DynamicAtom this[int index]
        => index < 0 || index >= _record.Length ? NULL : new DynamicAtom(_record[index]);

    protected override DynamicAtom this[string name]
        => _indexer.TryGetValue(name, out var index) ? new DynamicAtom(_record[index]) : NULL;

    protected override bool TryGetValue(string name, out object? value)
    {
        if (indexer.TryGetValue(name, out var index))
        {
            value = record[index];
            return true;
        }
        else
        {
            value = null;
            return false;
        }
    }

    public override IEnumerable<string> GetDynamicMemberNames()
        => _indexer.Keys;
}